package com.xcm.util;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * Base64工具类
 *
 * @author 林强
 * @date 2018-04-12 11:15
 */
public class Base64Utils {

    /**
     * 编码
     *
     * @param str     需要被编码的字符串
     * @param charset 字符编码
     * @return 返回编码后的字符串
     * @throws UnsupportedEncodingException
     */
    public static String encode(String str, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(charset)) {
            throw new NullPointerException("编码不能为空");
        }
        final Base64.Encoder encoder = Base64.getEncoder();
        final byte[] bytes = str.getBytes(charset);
        return encoder.encodeToString(bytes);
    }

    /**
     * 解码
     *
     * @param str 需要被解码的字符串
     * @return 被解码后的字符串
     * @throws UnsupportedEncodingException
     */
    public static String decode(String str) {
        final Base64.Decoder decoder = Base64.getDecoder();
        final byte[] decode = decoder.decode(str);
        return new String(decode);
    }

    public static void main(String[] args) {
        try {
            System.out.println(encode("http://localhost:8080/sysDepartment/list", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
